import DynamicElementDefinition from "./dynamic-element-definition";
import DynamicElementDefinitionConstant from "./dynamic-element-definition-constant";

export default class DynamicElementDefinitionFactory {
  /**
   * Gets all dynamic element definitions.
   */
  static getDefinitions(responseString: string): DynamicElementDefinition[] {
    const response = JSON.parse(responseString);
    const definitions: DynamicElementDefinition[] = [];
    let width = response.designWidth ?? 740;
    let height = response.designHeight ?? 1500;

    if (response.rootItemType.toLowerCase() === DynamicElementDefinitionConstant.cpSplitter.toLowerCase()) {
      for (const childIndex in response.rootObj.children) {
        if (response.rootObj.orientation == 1) {
          width = response.rootObj.sizes[childIndex]
        } else if (response.rootObj.orientation == 2) {
          height = response.rootObj.sizes[childIndex]
        }
        definitions.push(...this.extract(response.rootObj.children[childIndex], width, height));
      }
    } else if (response.rootItemType.toLowerCase() === DynamicElementDefinitionConstant.cpSplitItem.toLowerCase()) {
      definitions.push(...this.extract(response.rootObj.child, width, height));
    }

    return definitions;
  }

  /**
   * Extract element definitions from single node.
   */
  private static extract(node: any, width: any, height: any): DynamicElementDefinition[] {
    const definitions: DynamicElementDefinition[] = [];

    if (node.className.toLowerCase() === DynamicElementDefinitionConstant.cpSplitItem.toLowerCase()) {
      const calculateSize = this.calculateSize(width, height)
      definitions.push({
        type: node.url,
        config: node.child,
        width: calculateSize.width,
        height: calculateSize.height,
        width1: width,
        height1: height,
      });
    } else if (node.className.toLowerCase() === DynamicElementDefinitionConstant.cpSplitter.toLowerCase()) {
      for (const index in node.children) {
        if (node.orientation == 1) {
          width = node.sizes[index]
        } else if (node.orientation == 2) {
          height = node.sizes[index]
        }
        definitions.push(...this.extract(node.children[index], width, height));
      }
    }

    return definitions;
  }

  /**
   * 计算高度和宽度
   */
  private static calculateSize(width: any, height: any): any {
    const windowWidth = wx.getSystemInfoSync().windowWidth * 0.9;
    const windowHeight = windowWidth * (height / width);

    return { width: windowWidth, height: windowHeight }
  }
}